from django.shortcuts import render, get_object_or_404, redirect
from.models import Question, UserAnswer
from django.contrib.auth.decorators import login_required
from django.contrib import messages


# 练习题列表视图
def question_list(request):
    questions = Question.objects.all()
    return render(request, 'question_bank/question_list.html', {'questions': questions})


# 答题视图
@login_required
def answer_question(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    if request.method == 'POST':
        user_answer = request.POST.get('user_answer')
        is_correct = check_answer(question, user_answer)  # 假设存在一个函数用于判断答案对错
        UserAnswer.objects.create(
            user=request.user,
            question=question,
            user_answer=user_answer,
            is_correct=is_correct
        )
        if is_correct:
            messages.success(request, '回答正确！')
            return redirect('correct_answer', question_id=question_id)
        else:
            messages.error(request, '回答错误，再接再厉哦。')
            return redirect('incorrect_answer', question_id=question_id)
    return render(request, 'question_bank/answer_question.html', {'question': question})


# 判断答案对错的函数（示例，需根据具体题目类型和答案比较逻辑完善）
def check_answer(question, user_answer):
    return user_answer == question.answer


# 正确答案提示视图
def correct_answer(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    return render(request, 'question_bank/correct_answer.html', {'question': question})


# 错误答案提示视图
def incorrect_answer(request, question_id):
    question = get_object_or_404(Question, id=question_id)
    return render(request, 'question_bank/incorrect_answer.html', {'question': question})